﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
using System.IO;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public string text = "US usage Some authorities insist, prescriptively, which whichthat relative which should be used only in non-restrictive contexts. For restrictive contexts (e.g.The song that made the charts in 2004 is better than the later ones), they prefer that. Actual usage does not support this rule Fowler, who proposed the rule, himself acknowledged that it was not the practice of most or of the best writers. Even E.B. White, a notoriouswhich-hunter, wrote this: the premature expiration of a pig is, I soon discovered, a departure which the community marks solemnly on its calendar. In modern UK usage, The song which made the charts in 2004 is better than the later ones is generally accepted without question.";
        public MainWindow()
        {
            InitializeComponent();
            richTextBoxPreview.AppendText(text);
            //richTextBoxPreview.AppendText(OpenDocument(textFilePath);
        }

        /// <summary>
        /// Search the text for <param name="searchedWord" /> word <param name="searchedWord" />.
        /// </summary>
        /// <param name="searchedWord">The word to be searched</param>
        /// <returns></returns>
        private void Search(string searchedWord)
        {   
            var selection = richTextBoxPreview.Selection;
            var start = richTextBoxPreview.Document.ContentStart;
            var end = richTextBoxPreview.Document.ContentEnd;
            string lower = text.ToLowerInvariant();
            string[] words = GetSearchWords(lower);
            int count = 0;
            foreach (var word in words)
            {
                int i = count;
                if (words[i].Equals(searchedWord) == true)
                {
                    int startPosition = lower.IndexOf(words[i], lower.IndexOf(words[i - 1]));

                    int endPosition = lower.IndexOf(words[i], lower.IndexOf(words[i - 1])) + words[i].Length;
                    
                    string value = String.Format("... {0} {1} {2} ...",words[i - 1], text.Substring(startPosition, words[i].Length), words[i + 1]);

                    listViewResults.Items.Add(value);
                    selection.Select(start.GetPositionAtOffset(startPosition + 2), start.GetPositionAtOffset(endPosition + 2));
                    richTextBoxPreview.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
                    selection.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Red));
                }
                count++;

            }
        }


        /// <summary>
        /// Opens document from <param name="textFilePath" /> filepath <param name="textFilePath" />.
        /// </summary>
        /// <param name="textFilePath">path to document</param>
        /// <returns>Read document as a string</returns>
        private string OpenDocument(string textFilePath)
        {
            StreamReader streamReader = new StreamReader(textFilePath);
            string text = streamReader.ReadToEnd();
            streamReader.Close();
            return text;
        }

        /// <summary>
        /// Converts the string to array of words.
        /// </summary>
        /// <param name="text">The string of the text</param>
        /// <returns>String Array of all text words</returns>
        public static string[] GetSearchWords(string text)
        {
            string pattern = @"\S+";
            Regex re = new Regex(pattern);

            MatchCollection matches = re.Matches(text);
            string[] words = new string[matches.Count];
            for (int i = 0; i < matches.Count; i++)
            {
                words[i] = matches[i].Value;
            }
            return words;
        }


        private void listViewResults_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            double scrollPoint = 20.0;
            richTextBoxPreview.ScrollToVerticalOffset(scrollPoint);
        }

        private void textBoxSearchBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            
            if (textBoxSearchBox.Text != null)
            {
                listViewResults.Items.Clear();
                Search(textBoxSearchBox.Text.ToLower());
            }
        }

        //private void LoadFile()
        //{
           
            //FindWordInText();
        //}

        //private void FindWordInText()
        //{
        //    string word = "which";
        //    int end = 0;
        //    for (int i = 0; i < CountStringOccurrences(word); i++)
        //    {
        //        var start = richTextBoxPreview.Document.ContentStart;
                
        //        var startPosition = start.GetPositionAtOffset(text.IndexOf(word) + 1 + end);
        //        var endPosition = start.GetPositionAtOffset(text.IndexOf(word) + word.Length + 2 + end);
        //        end = end + text.IndexOf(word) + word.Length + 2;
                
        //        var selection = richTextBoxPreview.Selection;
        //        selection.Select(startPosition, endPosition);
        //        selection.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Red));
        //    }
        //}

        //private int CountStringOccurrences(string word)
        //{
        //    int count = 0;
        //    int i = 0;
        //    while ((i = text.IndexOf(word, i)) != -1)
        //    {
        //        i += word.Length;
        //        count++;
        //    }
        //    return count;
        //}

        
    }
}
